创建组件

第一步 创建库

首先要为组件创建一个库,执行命令:

1
ng generate lib hero-lib --tags=lib:content --directory=content  --routing --lazy --unit-test-runner jest --parent-module=apps/client/src/app/app.module.ts

[hero-lib] 库名
[--tags=lib:content] 会在项目的nx.json下记录的信息
[--directory=content] 会创建在libs/content目录中
[--routing] 添加路由
[--lazy] 延迟加载
[--unit-test-runner jest] 测试相关
[--parent-module=apps/client/src/app/app.module.ts] 会在这个文件中添加相关信息

创建库

此处选择css即可

第二布 创建组件

创建完库需要再创建库中的组件,执行命令:

1
ng generate component hero-list --project=content-hero-lib --prefix=chs-hero-list

[hero-list] 组件名
[--project=content-hero-lib] 属于哪个项目,就是上面命令中的项目名,在上一步执行完成后会在nx.json中添加
[--prefix=chs-hero-list] 前缀

第三步 配置路由

配置路由目的是将hero-list组件直接显示在首页上
首先执行命令添加路由

1
ng generate module app-routing --flat --module=app

然后修改路由文件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ContentHeroLibModule } from '@sample-app/content/hero-lib';

const routes: Routes = [
  {
    path: '', pathMatch: 'full',
    loadChildren: '@sample-app/content/hero-lib#ContentHeroLibModule'
  }
];

@NgModule({
  declarations: [],
  imports: [
    ContentHeroLibModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

这个路由将''路径交给了子路由管理
@sample-app/content/hero-lib#ContentHeroLibModule
[@sample-app/content/hero-lib]是在创建时在tsconfig.json中自动添加的信息
[#ContentHeroLibModule]是子路由的module名

修改子路由
content-hero-lib.module.ts:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { HeroListComponent } from './hero-list/hero-list.component';

@NgModule({
  imports: [
    CommonModule,

    RouterModule.forChild([
      {path: '', pathMatch: 'full', component: HeroListComponent}
    ])
  ],
  declarations: [HeroListComponent]     //别忘了将HeroListComponent添加到declarations中
})
export class ContentHeroLibModule {}

然后在app.component.html中将页面给路由管理:

1
<router-outlet></router-outlet>

然后运行项目显示:

创建组件

组件创建成功了